package com.hzmg.discovery;

import akka.actor.typed.ActorRef;
import akka.actor.typed.Behavior;
import akka.actor.typed.javadsl.AbstractBehavior;
import akka.actor.typed.javadsl.ActorContext;
import akka.actor.typed.javadsl.Behaviors;
import akka.actor.typed.javadsl.Receive;
import akka.http.javadsl.model.Uri;
import com.hzmg.akkacloud.worker.background.ReactiveDiscoveryClient;
import com.hzmg.route.RouteDefinition;
import com.hzmg.support.util.NameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

/**
 * 服务发现
 *
 * @author Yukoo
 */
public class DiscoveryClientRouteDefinitionLocator extends AbstractBehavior<String> {

    private static final Logger logger = LoggerFactory.getLogger(DiscoveryClientRouteDefinitionLocator.class);

    private final String routeIdPrefix;

    public DiscoveryClientRouteDefinitionLocator(ActorContext<String> context) {
        super(context);
        this.routeIdPrefix = ReactiveDiscoveryClient.class.getSimpleName() + "_";
    }

    public static Behavior<String> create() {
        return Behaviors.setup(DiscoveryClientRouteDefinitionLocator::new);
    }

    @Override
    public Receive<String> createReceive() {
        return newReceiveBuilder()
                .onMessage(String.class, this::onStart)
                .build();
    }

    private Behavior<String> onStart(String appName) {
/*        Map<String, WorkerInfo> appName2ServiceInstance =
                ReactiveDiscoveryClient.getWorkerInfosByAppName("akkcloud-client-demo");

        if (appName2ServiceInstance.isEmpty()) {
            logger.info("No registration service is found");
            return Behaviors.stopped();
        }*/

/*        for (Map.Entry<String, WorkerInfo> instanceEntry : appName2ServiceInstance.entrySet()) {

            RouteDefinition routeDefinition = new RouteDefinition();
            routeDefinition.setId(this.routeIdPrefix + instanceEntry.getKey());
            routeDefinition.setUri(Uri.create("lb://" + instanceEntry.getKey()));

            ActorRef<RouteDefinition> discoveryRef = getContext().spawn(DiscoveryPositioner.create()
                    , NameUtils.normalizeActorRefSimpleName(DiscoveryClientRouteDefinitionLocator.class));
            discoveryRef.tell(routeDefinition);
        }*/

        if (appName.isEmpty() || appName.equals("")) {
            logger.info("No registration service is found");
            return Behaviors.stopped();
        }

        RouteDefinition routeDefinition = new RouteDefinition();
        routeDefinition.setUri(Uri.create("lb://" + appName)); // 标识 URI


        ActorRef<RouteDefinition> discoveryRef = getContext().spawn(DiscoveryPositioner.create()
                , NameUtils.normalizeActorRefSimpleName(DiscoveryClientRouteDefinitionLocator.class));
        discoveryRef.tell(routeDefinition);

        return this;
    }
}
